

package com.platform.common.config;

import com.platform.common.core.Result;
import com.platform.common.exception.ApiException;
import com.platform.common.exception.PlatformBindException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 自定义错误处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlerResolver {


    /**
     * 全局异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleGlobalException(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return Result.failure(e.getLocalizedMessage());
    }

    /**
     * validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleBodyValidException(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.error("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
        return Result.failure(fieldErrors.get(0).getDefaultMessage());
    }

    @ExceptionHandler(PlatformBindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handlePlatformBindException(PlatformBindException e){
        log.error("platform异常信息 ex={}", e.getMessage(), e);
        return Result.failure(e.getMessage());
    }

    @ExceptionHandler(ApiException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleApiException(ApiException e){
        log.error("ApiException异常信息 ex={}", e.getMessage(), e);
        return Result.failure(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Object notFount(RuntimeException e) {
        log.info("运行时异常:", e);
        return Result.failure(e.getMessage());
    }




}
